package com.liuzhilong.infrastructure.framework.netty.api.standard.codec;

import com.liuzhilong.infrastructure.framework.netty.api.standard.command.Command;
import com.liuzhilong.infrastructure.framework.netty.api.standard.command.CommandType;
import io.netty.buffer.ByteBuf;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * command格式的预存信息，用于从字节流中读取信息
 */
@Data
@Accessors(chain = true)
public  final  class CommandCodec{
    private byte type;
    private int bodyLength;

    /**
     * 校验magic信息
     * @param magic magicword
     * @return 是否和command的相同
     */
    public static boolean checkMagic(byte magic){
        if (magic != Command.MAGIC_WORD) {
            return false;
        }
        return true;
    }

    /**
     * 将一个command编码并写入到{@link ByteBuf}中
     * @param command
     * @param out
     */
    public static void encodeTo(Command command,ByteBuf out){
        //写入magicword
        out.writeByte(Command.MAGIC_WORD);
        //写入type
        out.writeByte(command.getType().ordinal());
        //写入body长度
        out.writeInt(command.getBody().length);
        //写入body
        out.writeBytes(command.getBody());
    }

    /**
     * 转化为 Command
     * @param body
     * @return
     */
    public Command finallyToCommand(byte[] body){
        return new Command()
                .setType(CommandType.toCommandType(this.type))
                .setBody(body);
    }






}